<template>
  <div class="app-container-flex">
    <NewFullScreen v-model="showDialog" :title="title" @returnBack="returnBack">
      <template v-slot:full-button>
        <el-button @click="save()" :disabled="!canSave">保存</el-button>
      </template>
      <div class="batch-content">
        <div class="batch-content-item-left" v-if="businessType === '1'">
          <div class="model-panel">
            <div class="model-panel-title">
              <p>供应商</p>
            </div>
          </div>
          <ul v-if="tableInfo.supplierOptions.length">
            <li
              v-for="item in tableInfo.supplierOptions"
              :key="item.id"
              @click="checkSupplier(item)"
              class="supplier-item"
              :class="
                item.id === formInfo.data.supplierId
                  ? 'supplier-item-checked'
                  : ''
              "
            >
              {{ item.name }}
            </li>
          </ul>
        </div>
        <div class="batch-content-item-right">
          <div class="model-panel">
            <div class="model-panel-title">
              <p>{{ $t('basic_information') }}</p>
            </div>
            <div class="model-panel-body">
              <!-- form -->
              <PageForm
                class="paddingBox order-model-formBox flex_wrap_start_start"
                v-model:ref-obj="formInfo.ref"
                :disabled="formInfo.disabled"
                v-model:data="formInfo.data"
                :field-list="formInfo.fieldList"
                :rules="formInfo.rules"
                :label-width="formInfo.labelWidth"
              >
                <template v-slot:form-storeDepotName>
                  <el-input
                    class="not-mongolia"
                    type="input"
                    :required="true"
                    :disabled="true"
                    placeholder="请选择仓库"
                    v-model="formInfo.data.storeDepotName"
                  >
                    <template #append>
                      <el-icon @click="selectStoreDepot"
                        ><MoreFilled
                      /></el-icon>
                    </template>
                  </el-input>
                </template>
                <template v-slot:form-consumeDeptName>
                  <el-input
                    class="not-mongolia"
                    type="input"
                    :disabled="true"
                    placeholder="请选择消耗部门"
                    v-model="formInfo.data.consumeDeptName"
                  >
                    <template #append>
                      <el-icon @click="selectConsumeDept"
                        ><MoreFilled
                      /></el-icon>
                    </template>
                  </el-input>
                </template>
                <template v-slot:form-useApplicationOrderNo>
                  <el-input
                    class="not-mongolia"
                    type="input"
                    :disabled="true"
                    placeholder="请选择申请单号"
                    v-model="formInfo.data.useApplicationOrderNo"
                  >
                    <template #append>
                      <el-icon @click="openUseApplication"
                        ><MoreFilled
                      /></el-icon>
                    </template>
                  </el-input>
                </template>
              </PageForm>
            </div>
          </div>

          <div class="model-panel">
            <div class="model-panel-title">
              <Tooltip :text="$t('detailInfo')"></Tooltip>
            </div>
            <div class="model-panel-body">
              <!-- 条件栏 -->

              <NewPageFilter
                v-model:query="filterInfo.query"
                :filter-btn="filterInfo.list"
              >
                <template v-slot:filter-removeProduct>
                  <el-button
                    :disabled="!canRemoveProduct"
                    @click="removeProduct"
                    >删除产品</el-button
                  >
                </template>
                <template v-slot:filter-setLocation>
                  <el-button
                    :disabled="!canSetLocation"
                    @click="openStoreLocationNo"
                    v-if="showSetLocation"
                    >批量设置货位</el-button
                  >
                </template>
              </NewPageFilter>
              <div class="flex_full_item">
                <!-- 表格 -->

                <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
                  <PageTable
                    ref="batchDataTable"
                    v-model:query="filterInfo.query"
                    :refresh="tableInfo.refresh"
                    :init-curpage="tableInfo.initCurpage"
                    v-model:data="tableInfo.data"
                    :pager="false"
                    :field-list="tableInfo.fieldList"
                    :handle="tableInfo.handle"
                    :isDynamic="true"
                    @handleEvent="handleEvent"
                  >
                    <template v-slot:col-qty="scope">
                      <el-form-item
                        class="margin-bottom"
                        v-if="
                          formInfo.isCargoSpaceManage === 1
                            ? !scope.row.emptyRowType
                            : (scope.row.codeType === 1 ||
                                scope.row.codeType === 4) &&
                              !scope.row.emptyRowType
                        "
                      >
                        <div class="page-table-input-number-wrapper">
                          <div class="page-table-input-number-left">
                            <div class="page-table-input-number-item">
                              <el-form-item
                                :prop="`data.${scope.$index}.largeUnitQty`"
                                :rules="
                                  scope.$index >= 0
                                    ? [
                                        {
                                          validator: $validate.positiveAndZero,
                                          trigger: 'blur',
                                        },
                                      ]
                                    : []
                                "
                              >
                                <el-input-number
                                  style="width: 100%; margintop: 18px"
                                  v-model.lazy="scope.row.largeUnitQty"
                                  clearable
                                  controls-position="right"
                                  :precision="
                                    scope.row.qtyOperateMode === 0 ||
                                    scope.row.qtyOperateMode === 2
                                      ? 0
                                      : systemConfig.qty_show_precision
                                  "
                                  @change="
                                    changeLarge(
                                      $event,
                                      scope.row,
                                      `data.${scope.$index}.largeUnitQty`,
                                      scope.$index
                                    )
                                  "
                                  :min="0"
                                  :max="largeMax(scope.row)"
                                />
                              </el-form-item>
                              <!-- <div class="page-table-input-number-item-unite">
                            {{ scope.row.unitName }}
                          </div> -->
                            </div>
                            <div
                              class="page-table-input-number-item"
                              v-if="
                                scope.row.unitConvertCoefficient > 1 &&
                                scope.row.qtyOperateMode === 2
                              "
                            >
                              <el-form-item>
                                <el-input-number
                                  style="width: 100%; margintop: 18px"
                                  v-model.lazy="scope.row.smallUnitQty"
                                  clearable
                                  controls-position="right"
                                  :precision="0"
                                  :min="0"
                                  :max="smallMax(scope.row)"
                                  @change="
                                    changeSmall(
                                      $event,
                                      scope.row,
                                      `data.${scope.$index}.smallUnitQty`,
                                      scope.$index
                                    )
                                  "
                                />
                              </el-form-item>
                              <!-- <div class="page-table-input-number-item-unite">
                            {{ scope.row.calcUnitName }}
                          </div> -->
                            </div>
                          </div>
                          <div
                            class="page-table-input-number-right"
                            v-if="scope.row.qtyOperateMode === 2"
                          >
                            {{ $fn.qtyFormatter(scope.row.qty) }}
                          </div>
                        </div>
                      </el-form-item>
                      <span
                        v-else-if="
                          formInfo.isCargoSpaceManage === 1
                            ? false
                            : (scope.row.codeType === 2 ||
                                scope.row.codeType === 3) &&
                              !scope.row.emptyRowType
                        "
                        >{{ $fn.qtyFormatter(scope.row.qty) }}</span
                      >
                    </template>
                    <template v-slot:col-reason="scope">
                      <el-input
                        v-if="formInfo.data.businessType === '10'"
                        v-model="scope.row.reason"
                        :maxlength="25"
                        @change="changeData($event, scope.row)"
                        @input="(e) => (scope.row.reason = validSe(e))"
                      />
                      <SelectModel
                        v-if="formInfo.data.businessType === '1'"
                        v-model.lazy="scope.row.reason"
                        style="margintop: 18px"
                        type-code="purch_return_reason"
                        @change="changeData($event, scope.row)"
                      />
                    </template>
                    <template v-slot:col-storeBatchNumber="scope">
                      <StoreBatchNumberTag :row="scope.row" />
                    </template>
                    <template v-slot:col-targetLocationNo="scope">
                      <el-form-item
                        :prop="`data.${scope.$index}.targetLocationNo`"
                        :rules="
                          scope.$index >= 0
                            ? [
                                {
                                  required: true,
                                  trigger: 'change',
                                  message: '请选择转入货位',
                                },
                              ]
                            : []
                        "
                      >
                        <el-input
                          class="not-mongolia"
                          type="input"
                          :disabled="true"
                          placeholder="请选择转入货位"
                          v-model="scope.row.targetLocationNo"
                        >
                          <template #append>
                            <el-icon
                              @click="selectTargetLocationNoRow(scope.row)"
                              ><MoreFilled
                            /></el-icon>
                          </template>
                        </el-input>
                      </el-form-item>
                    </template>
                  </PageTable>
                </el-form>
              </div>
            </div>
          </div>
          <!-- 仓库 -->
          <SelectDepot
            v-if="selectStoreDepotInfo.visible"
            v-model:showDialog="selectStoreDepotInfo.visible"
            :checkBox="false"
            :query="selectStoreDepotInfo.query"
            :highlightRow="true"
            :checkLock="true"
            :saveEmpty="true"
            @callback="selectStoreDepotCallBack"
          />
          <select-dept
            v-if="deptInfo.visible"
            v-model:showDialog="deptInfo.visible"
            :query="deptInfo.query"
            @callback="selectDeptCallback"
            :checkBox="false"
            :highlightRow="true"
            :saveEmpty="true"
          />
        </div>
      </div>
    </NewFullScreen>
    <individual
      v-if="individualInfo.visible"
      v-model:visible="individualInfo.visible"
      :tableRow="individualInfo.tableRow"
      :details="individualInfo.details"
      :leftApi="individualInfo.leftApi"
      :leftQuery="individualInfo.leftQuery"
      :rightQuery="individualInfo.rightQuery"
      :rightApi="individualInfo.rightApi"
      :leftTableKey="individualInfo.leftTableKey"
      :rightTableKey="individualInfo.rightTableKey"
      :isGetRight="individualInfo.tableRow.isGetRight"
      :businessType="formInfo.data.businessType"
      @callback="individualCallback"
    ></individual>
    <selectUseApplication
      v-if="selectUseApplicationInfo.visible"
      v-model:showDialog="selectUseApplicationInfo.visible"
      :query="selectUseApplicationInfo.query"
      @callback="selectUseApplicationCallback"
    />
    <SelectCargoSpace
      v-if="selectLocationNoInfo.visible"
      v-model:show-dialog="selectLocationNoInfo.visible"
      row-key="goodsLocationId"
      v-model:query="selectLocationNoInfo.query"
      :highlightRow="true"
      :checkBox="false"
      :save-empty="false"
      :showDepot="false"
      @callback="selectLocationNoCallBack"
    />
    <SelectCargoSpace
      v-if="selectLocationNoRowInfo.visible"
      v-model:show-dialog="selectLocationNoRowInfo.visible"
      row-key="goodsLocationId"
      v-model:query="selectLocationNoRowInfo.query"
      :highlightRow="true"
      :checkBox="false"
      :save-empty="true"
      :showDepot="false"
      @callback="selectLocationNoRowCallBack"
    />
  </div>
</template>

<script setup name="batchData">
import {
  getInventoryDetailsCustomizeListAll,
  getInventoryDetailsCustomizeListPage,
  inventoriesInsertInventoryLossBusiness,
} from '@/api/stock'
import _ from 'lodash'
import individual from './individual'
import selectUseApplication from './selectUseApplication'
import StoreBatchNumberTag from '@/views/stock/components/StoreBatchNumberTag'
import { getCustomizeSetting } from '@/api/customize'
import {
  setDisableTime,
  _getCurrentFiscalPeriod,
} from '@/common/js/dateOperation'
const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: '出库处理',
  },
  selectionsData: {
    type: Array,
    default: () => {
      return []
    },
  },
  baseData: {
    type: Object,
    default: () => {
      return {}
    },
  },
  orderId: {
    type: Number,
  },
  isConsignBusiness: {
    type: Number,
  },
  businessType: {
    type: String,
    default: '',
  },
})
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const showSetLocation = ref(false)
const selectLocationNoInfo = ref({
  visible: false,
  query: {
    status: '1',
    deportId: '',
    idNotIn: '',
  },
})
const selectLocationNoRowInfo = ref({
  visible: false,
  row: {},
  query: {
    status: '1',
    deportId: '',
    idNotIn: '',
  },
})
const formRefs = ref([])
const formInfo = ref({
  ref: null,
  data: {},
  fieldList: [
    // {
    //   label: '业务类型',
    //   value: 'businessType',
    //   type: 'select-model',
    //   code: 'inventory_loss_business_type',
    //   checkDefault: false,
    //   event: 'businessType',
    // },
  ],
  cloneFieldList: [
    {
      label: '业务日期',
      value: 'businessDate',
      type: 'date',
      clearable: false,
    },
    { label: '备注', value: 'remark', type: 'input' },
  ],
  rules: {
    businessType: [
      { required: true, message: '请选择业务类型', trigger: 'change' },
    ],
    businessDate: [
      { required: true, message: '请选择业务日期', trigger: 'change' },
    ],
    storeDepotName: [
      { required: true, message: '请选择仓库', trigger: 'change' },
    ],
    consumeDeptName: [
      { required: true, message: '请选择消耗部门', trigger: 'change' },
    ],
    useApplicationOrderNo: [
      { required: true, message: '请选择申请单号', trigger: 'change' },
    ],
    returnType: [
      { required: true, message: '请选择采购退货类型', trigger: 'change' },
    ],
    phone: [{ validator: proxy.$validate.cellphone, trigger: 'change,blur' }],
  },
  labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {
      diffQty: {
        queryType: 'LESS_THAN',
        value: 0,
      },
      orderId: {
        queryType: 'EQUALS',
        value: props.orderId,
      },
      depotStockId: {
        queryType: 'NOT_EQUAL',
        value: -2,
      },
      id: {
        queryType: 'IN',
        value: null,
      },
    },
    queryParams: {
      stockAvailableCalcQtyGt: 0,
      useApplicationId: '',
      isInventoryLossBusiness: '',
    },
  },
  list: [
    { type: 'slot', value: 'removeProduct' },
    { type: 'slot', value: 'setLocation' },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  fieldList: [],
  sysGroup: [],
  supplierOptions: [],
  supplierGroupData: [],
  tableKey:
    'stockInventoryExportData-com.slip.spd.entity.vo.stock.InventoryOrderDetailVO',
  handle: {
    fixed: 'right',
    label: '操作',
    width: '150',
    btList: [
      {
        label: '个体操作',
        event: individualDetail,
        show: true,
        ifRender: function (row) {
          return (
            (row.codeType === 2 || row.codeType === 3) && row.diffCalcQty > 0
          )
        },
      },
      {
        label: '删除',
        popconfirmText: '删除后将改变数据,是否继续？',
        event: removeProduct,
        show: true,
      },
    ],
  },
})
const individualInfo = ref({
  visible: false,
  index: 0,
  tableRow: {},
  details: {},
  leftApi: getInventoryDetailsCustomizeListPage,
  rightApi: getInventoryDetailsCustomizeListAll,
  leftQuery: {
    queryMap: {
      diffQty: {
        queryType: 'LESS_THAN',
        value: 0,
      },
      orderId: {
        queryType: 'EQUALS',
        value: props.orderId,
      },
      id: {
        queryType: 'NOT_IN',
        value: null,
      },
      depotStockId: {
        queryType: 'NOT_EQUAL',
        value: -2,
      },
      storeBatchNumber: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      price: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      supplierId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      productId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      batchNumber: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        ignoreEmptyValue: false,
        value: null,
      },
      productionDate: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        ignoreEmptyValue: false,
        value: null,
      },
      validityDate: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        ignoreEmptyValue: false,
        value: null,
      },
    },
    queryParams: {},
  },
  rightQuery: {
    queryMap: {
      diffQty: {
        queryType: 'LESS_THAN',
        value: 0,
      },
      orderId: {
        queryType: 'EQUALS',
        value: props.orderId,
      },
      id: {
        queryType: 'IN',
        value: null,
      },
      depotStockId: {
        queryType: 'NOT_EQUAL',
        value: -2,
      },
    },
    queryParams: {},
  },
  leftTableKey:
    'stockInventoryExportDataIndividualLeft-com.slip.spd.entity.vo.stock.InventoryOrderDetailVO',
  rightTableKey:
    'stockInventoryExportDataIndividualRight-com.slip.spd.entity.vo.stock.InventoryOrderDetailVO',
})
const selectStoreDepotInfo = ref({
  visible: false,
  query: {
    depotAuth: 'id',
    useTypeId: '1',
    status: 1,
    subDepotId: '',
    idNot: props.baseData.depotId,
    isCargoSpaceManage: 0,
  },
})
const deptInfo = reactive({
  visible: false,
  query: {
    deptAuth: 'id',
    status: '1',
  },
})
const selectUseApplicationInfo = ref({
  visible: false,
  query: {
    exportDepotId: {
      queryType: 'EQUALS',
      value: props.baseData.depotId,
    },
  },
})
const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    emits('update:visible', val) // 更新父组件visible
  },
})
const canSave = computed(() => {
  return tableInfo.value.data.length
})
const canRemoveProduct = computed(() => {
  return tableInfo.value.selections.length
})
const canSetLocation = computed(() => {
  return tableInfo.value.selections.length
})

onMounted(() => {
  let obj = {
    qty: {
      label: '数量',
      value: 'qty',
      type: 'slot',
      hidden: true,
    },
    price: {
      label: '单价',
      value: 'price',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('inventories:price'),
      hidden: true,
    },
    sumAmount: {
      label: '盘点金额',
      value: 'sumAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('inventories:price'),
      hidden: true,
      show: false,
    },
    defaultSupplierPrice: {
      label: '默认供应商价格',
      value: 'defaultSupplierPrice',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('inventories:price'),
      hidden: true,
      show: false,
    },
    diffSumAmount: {
      label: '盘点差异金额',
      value: 'diffSumAmount',
      type: 'column',
      permission: !proxy.$permission('inventories:price'),
      formatter: proxy.$fn.TripartiteMethod,
      hidden: true,
      show: false,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  filterInfo.value.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  proxy.$nextTick(() => {
    formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
  })
  getCustomize()
  formHandleEvent('businessType', props.businessType)
  setBusinessDate()
})

let disStartDate = ref('')
let disEndDate = ref('')
async function setBusinessDate() {
  formInfo.value.data.businessDate = await _getCurrentFiscalPeriod(
    formInfo.value.fieldList,
    proxy,
    disStartDate,
    disEndDate
  )
}
function returnBack() {
  emits('returnBack')
}
function largeMax(row) {
  if (row.qtyOperateMode === 2) {
    return parseInt(row.diffCalcQty / row.unitConvertCoefficient)
  } else {
    return row.diffQty
  }
}
function smallMax(row) {
  let largeUnitQty = parseInt(row.diffCalcQty / row.unitConvertCoefficient)
  if (largeUnitQty === 0 || row.largeUnitQty === largeUnitQty) {
    return parseInt(row.diffCalcQty % row.unitConvertCoefficient)
  } else {
    return row.unitConvertCoefficient - 1
  }
}
function changeLarge(e, row, str, index) {
  proxy.$refs.tableForm.clearValidate(str)
  let largeUnitQty = parseInt(row.diffCalcQty / row.unitConvertCoefficient)
  if (row.qtyOperateMode === 2 && row.unitConvertCoefficient > 1) {
    if (largeUnitQty > 0 && e === largeUnitQty) {
      let smallUnitQty = parseInt(row.diffCalcQty % row.unitConvertCoefficient)
      if (row.smallUnitQty > smallUnitQty) {
        row.smallUnitQty = smallUnitQty
        if (props.businessType === '1') {
          tableInfo.value.supplierGroupData[formInfo.value.data.supplierId][
            index
          ] = row
        }
      }
    }
  }

  if (row.codeType === 1 || row.codeType === 4) {
    row.calcQty = proxy.$fn.accAdd(
      proxy.$fn.accMul(row.largeUnitQty || 0, row.unitConvertCoefficient || 1),
      row.smallUnitQty || 0
    )
    row.qty = proxy.$fn.accDiv(
      row.calcQty || 0,
      row.unitConvertCoefficient || 1
    )
    row.sumAmount = proxy.$fn.accDiv(
      proxy.$fn.accMul(row.calcQty || 0, parseFloat(row.price || 0)),
      row.unitConvertCoefficient || 1
    )
    row.details[0].largeUnitQty = row.largeUnitQty
    row.details[0].smallUnitQty = row.smallUnitQty
    row.details[0].calcQty = row.calcQty
    row.details[0].qty = row.qty
    row.details[0].sumAmount = row.sumAmount
    if (props.businessType === '1') {
      tableInfo.value.supplierGroupData[formInfo.value.data.supplierId][index] =
        row
    }
  }
}
function changeSmall(e, row, str, index) {
  proxy.$refs.tableForm.clearValidate(str)
  if (row.codeType === 1 || row.codeType === 4) {
    row.calcQty = proxy.$fn.accAdd(
      proxy.$fn.accMul(row.largeUnitQty || 0, row.unitConvertCoefficient || 1),
      row.smallUnitQty || 0
    )
    row.qty = proxy.$fn.accDiv(
      row.calcQty || 0,
      row.unitConvertCoefficient || 1
    )
    row.sumAmount = proxy.$fn.accDiv(
      proxy.$fn.accMul(row.calcQty || 0, parseFloat(row.price || 0)),
      row.unitConvertCoefficient || 1
    )
    row.details[0].largeUnitQty = row.largeUnitQty
    row.details[0].smallUnitQty = row.smallUnitQty
    row.details[0].calcQty = row.calcQty
    row.details[0].qty = row.qty
    row.details[0].sumAmount = row.sumAmount
    if (props.businessType === '1') {
      tableInfo.value.supplierGroupData[formInfo.value.data.supplierId][index] =
        row
    }
  }
}
function openStoreLocationNo() {
  let num = formInfo.value.data.businessType
  if (num == '2' || num === '34') {
    if (!formInfo.value.data.storeDepotId) {
      proxy.$message({
        message: `请选择入库仓库`,
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
      return
    }
    selectLocationNoInfo.value.query.depotId = formInfo.value.data.storeDepotId
  }
  selectLocationNoInfo.value.visible = true
}
function selectLocationNoCallBack(data) {
  if (data && data.id) {
    tableInfo.value.selections.forEach((item) => {
      item.targetLocationNo = data.locationNo
      item.targetGoodsLocationId = data.id
      item.targetLocationTypeValue = data.locationTypeValue
      item.targetLocationType = data.locationType
      item.details?.forEach((el) => {
        el.targetLocationNo = data.locationNo
        el.targetGoodsLocationId = data.id
        el.targetLocationTypeValue = data.locationTypeValue
        el.targetLocationType = data.locationType
      })
    })
    proxy.$refs.batchDataTable.clearSelection()
  }
}
function selectTargetLocationNoRow(row) {
  let num = formInfo.value.data.businessType
  if (num == '2' || num === '34') {
    if (!formInfo.value.data.storeDepotId) {
      proxy.$message({
        message: `请选择入库仓库`,
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
      return
    }
    selectLocationNoRowInfo.value.query.depotId =
      formInfo.value.data.storeDepotId
  }
  selectLocationNoRowInfo.value.visible = true
  selectLocationNoRowInfo.value.row = row
  selectLocationNoRowInfo.value.query.idNotIn = row.targetGoodsLocationId || ''
}
function selectLocationNoRowCallBack(data) {
  if (data && data.id) {
    selectLocationNoRowInfo.value.row.targetLocationNo = data.locationNo
    selectLocationNoRowInfo.value.row.targetGoodsLocationId = data.id
    selectLocationNoRowInfo.value.row.targetLocationTypeValue =
      data.locationTypeValue
    selectLocationNoRowInfo.value.row.targetLocationType = data.locationType
    selectLocationNoRowInfo.value.row.details?.forEach((el) => {
      el.targetLocationNo = data.locationNo
      el.targetGoodsLocationId = data.id
      el.targetLocationTypeValue = data.locationTypeValue
      el.targetLocationType = data.locationType
    })
  } else {
    selectLocationNoRowInfo.value.row.targetLocationNo = ''
    selectLocationNoRowInfo.value.row.targetGoodsLocationId = ''
    selectLocationNoRowInfo.value.row.targetLocationTypeValue = ''
    selectLocationNoRowInfo.value.row.targetLocationType = ''
    selectLocationNoRowInfo.value.row.details?.forEach((el) => {
      el.targetLocationNo = ''
      el.targetGoodsLocationId = ''
      el.targetLocationTypeValue = ''
      el.targetLocationType = ''
    })
  }
}
function changeData(val, row) {
  //原因变化
  if (row && row.details && row.details.length) {
    row.details.forEach((item) => {
      item.reason = val
    })
  }
  if (props.businessType === '1') {
    tableInfo.value.supplierGroupData[formInfo.value.data.supplierId].forEach(
      (item) => {
        if (item.id === row.id) {
          item = row
        }
      }
    )
  }
}
function setInfoAndList(num) {
  formInfo.value.fieldList = [
    // {
    //   label: '业务类型',
    //   value: 'businessType',
    //   type: 'select-model',
    //   code: 'inventory_loss_business_type',
    //   checkDefault: false,
    //   event: 'businessType',
    // },
  ]
  let arr = []
  const defaultInfo = props.baseData
  if (num === '25') {
    // 消耗
    arr = [
      {
        label: '出库仓库',
        value: 'exportDepotName',
        type: 'input',
        disabled: true,
      },
      {
        label: '出库部门',
        value: 'deptName',
        type: 'input',
        disabled: true,
      },
      {
        label: '消耗部门',
        value: 'consumeDeptName',
        type: 'slot',
      },
    ]
    const keyObj = {
      exportDepotName: 'depotName',
      exportDepotId: 'depotId',
      exportDeptName: 'deptName',
      exportDeptId: 'deptId',
    }
    formInfo.value.data.consumeDeptId = proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.id
      : ''
    formInfo.value.data.consumeDeptName = proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.name
      : ''
    setFormInfo(keyObj, defaultInfo)
  } else if (num === '2') {
    // 移库
    arr = [
      {
        label: '出库仓库',
        value: 'exportDepotName',
        type: 'input',
        disabled: true,
      },
      {
        label: '出库部门',
        value: 'exportDeptName',
        type: 'input',
        disabled: true,
      },
      { label: '入库仓库', value: 'storeDepotName', type: 'slot' },
      {
        label: '入库部门',
        value: 'storeDeptName',
        type: 'input',
        disabled: true,
      },
    ]
    const keyObj = {
      exportDepotName: 'depotName',
      exportDepotId: 'depotId',
      exportDeptName: 'deptName',
      exportDeptId: 'deptId',
    }
    setFormInfo(keyObj, defaultInfo)
  } else if (num === '1') {
    // 采购退货
    arr = [
      {
        label: '退货仓库',
        value: 'exportDepotName',
        type: 'input',
        disabled: true,
      },
      {
        label: '退货部门',
        value: 'exportDeptName',
        type: 'input',
        disabled: true,
      },
      {
        label: '采购退货类型',
        value: 'returnType',
        type: 'select-model',
        code: 'purch_return_type',
        required: true,
      },
      {
        label: '退货供应商',
        value: 'supplierName',
        type: 'input',
        disabled: true,
      },
      { label: '供应商联系人', value: 'contact', type: 'input', maxlength: 32 },
      { label: '供应商联系电话', value: 'phone', type: 'input' },
    ]
    const keyObj = {
      exportDepotName: 'depotName',
      exportDepotId: 'depotId',
      exportDeptName: 'deptName',
      exportDeptId: 'deptId',
    }
    setFormInfo(keyObj, defaultInfo)
  } else if (num === '34') {
    // 领用退回
    defaultInfo.operateUserName = proxy.$store.state.user.userInfo.user
      ? proxy.$store.state.user.userInfo.user.name
      : ''
    defaultInfo.operateUser = proxy.$store.state.user.userInfo.user
      ? proxy.$store.state.user.userInfo.user.id
      : ''
    arr = [
      {
        label: '退回人',
        value: 'operateUserName',
        type: 'input',
        disabled: true,
      },
      {
        label: '退出仓库',
        value: 'exportDepotName',
        type: 'input',
        disabled: true,
      },
      {
        label: '退出部门',
        value: 'exportDeptName',
        type: 'input',
        disabled: true,
      },
      { label: '退入仓库', value: 'storeDepotName', type: 'slot' },
      {
        label: '退入部门',
        value: 'storeDeptName',
        type: 'input',
        disabled: true,
      },
    ]
    const keyObj = {
      operateUserName: 'operateUserName',
      operateUser: 'operateUser',
      exportDepotName: 'depotName',
      exportDepotId: 'depotId',
      exportDeptName: 'deptName',
      exportDeptId: 'deptId',
    }
    setFormInfo(keyObj, defaultInfo)
  } else if (num === '10') {
    // 报废
    arr = [
      {
        label: '出库仓库',
        value: 'exportDepotName',
        type: 'input',
        disabled: true,
      },
      {
        label: '出库部门',
        value: 'exportDeptName',
        type: 'input',
        disabled: true,
      },
    ]
    const keyObj = {
      exportDepotName: 'depotName',
      exportDepotId: 'depotId',
      exportDeptName: 'deptName',
      exportDeptId: 'deptId',
    }
    setFormInfo(keyObj, defaultInfo)
  } else if (num === '20') {
    // 领用出库
    arr = [
      { label: '申请单号', value: 'useApplicationOrderNo', type: 'slot' },
      {
        label: '领用人',
        value: 'operateUserName',
        type: 'input',
        disabled: true,
      },
      {
        label: '领用部门',
        value: 'storeDeptName',
        type: 'input',
        disabled: true,
      },
      {
        label: '领入仓库',
        value: 'storeDepotName',
        type: 'input',
        disabled: true,
      },
      {
        label: '领出仓库',
        value: 'exportDepotName',
        type: 'input',
        disabled: true,
      },
    ]
    const keyObj = {
      exportDepotName: 'depotName',
      exportDepotId: 'depotId',
      exportDeptName: 'deptName',
      exportDeptId: 'deptId',
    }
    setFormInfo(keyObj, defaultInfo)
  }
  formInfo.value.fieldList = formInfo.value.fieldList.concat(
    arr.concat(proxy.$fn.deepClone(formInfo.value.cloneFieldList))
  )
  setDisableTime(formInfo.value.fieldList, disStartDate, disEndDate)
}
function setTableFieldList(num) {
  tableInfo.value.fieldList.forEach((item) => {
    if (item.value === 'useApplicationQty') {
      item.hidden = true
    }
    if (num === '2') {
      if (item.value === 'qty') {
        item.label = '移库数量'
      }
      if (item.value === 'sumAmount') {
        item.label = '移库金额'
      }
      if (item.value === 'reason') {
        item.hidden = true
      }
    } else if (num === '20') {
      if (item.value === 'qty') {
        item.label = '出库数量'
      }
      if (item.value === 'sumAmount') {
        item.label = '出库金额'
      }
      if (item.value === 'reason') {
        item.hidden = true
      }
      if (item.value === 'useApplicationQty') {
        item.hidden = false
      }
    } else if (num === '34') {
      if (item.value === 'qty') {
        item.label = '退回数量'
      }
      if (item.value === 'sumAmount') {
        item.label = '退回金额'
      }
      if (item.value === 'reason') {
        item.hidden = true
      }
    } else if (num === '25') {
      if (item.value === 'qty') {
        item.label = '消耗数量'
      }
      if (item.value === 'sumAmount') {
        item.label = '消耗金额'
      }
      if (item.value === 'reason') {
        item.hidden = true
      }
    } else if (num === '1') {
      if (item.value === 'qty') {
        item.label = '退货数量'
      }
      if (item.value === 'sumAmount') {
        item.label = '退货金额'
      }
      if (item.value === 'reason') {
        item.hidden = false
        item.label = '退货原因'
        item.type = 'slot'
      }
    } else if (num === '10') {
      if (item.value === 'qty') {
        item.label = '报废数量'
      }
      if (item.value === 'sumAmount') {
        item.label = '报废金额'
      }
      if (item.value === 'reason') {
        item.hidden = false
        item.label = '报废原因'
        item.type = 'slot'
      }
    }
    if (item.value === 'storeBatchNumber') {
      item['type'] = 'slot'
    }
  })
}
function getCustomize() {
  let param = {
    tableKey: tableInfo.value.tableKey,
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      let index = tableInfo.value.fieldList.findIndex(
        (item) => item.value === 'diffQty'
      )
      if (index > -1) {
        let obj = {
          label: '领用出库数',
          value: 'useApplicationQty',
          type: 'column',
          componentType: 'number',
          formatter: proxy.$fn.qtyFormatter,
          show: false,
          hidden: true,
        }
        tableInfo.value.fieldList.splice(index, 0, obj)
      }
      let locationNoindex = tableInfo.value.fieldList.findIndex(
        (item) => item.value === 'storeBatchNumber'
      )
      if (locationNoindex > -1) {
        let obj = {
          label: '转入货位',
          value: 'targetLocationNo',
          componentType: 'input',
          show: false,
          type: 'slot',
          hidden: true,
        }
        tableInfo.value.fieldList.splice(locationNoindex + 1, 0, obj)
      }
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.value.searchList,
        data.detail
      )
      filterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.value.query.queryMap,
      }
      filterInfo.value.query.customizeUserVO = data
      formInfo.value.data.businessType = props.businessType
      getList()
    }
  })
}
function getList(id = undefined) {
  if (id) {
    filterInfo.value.query.queryParams.isInventoryLossBusiness = 1
    filterInfo.value.query.queryParams.useApplicationId = id
  } else {
    filterInfo.value.query.queryParams.isInventoryLossBusiness = ''
    filterInfo.value.query.queryParams.useApplicationId = ''
  }
  let ids = props.selectionsData.map((item) => item.groupConcatIds)
  filterInfo.value.query.queryMap.id.value = ids.toString()
  getInventoryDetailsCustomizeListAll(filterInfo.value.query).then((res) => {
    if (res && res.success) {
      res.data.forEach((item) => {
        let unitConvertCoefficient = item.unitConvertCoefficient || 1
        if (id) {
          item.diffCalcQty = proxy.$fn.deepClone(
            item.useApplicationAvailableCalcQty || 0
          )
          item.diffQty = proxy.$fn.deepClone(
            item.useApplicationAvailableQty || 0
          )
        } else {
          item.diffQty = Math.abs(item.diffQty || 0)
          item.diffCalcQty = Math.abs(item.diffCalcQty || 0)
          item.qty = proxy.$fn.deepClone(item.diffQty)
          item.calcQty = proxy.$fn.deepClone(item.diffCalcQty)
          item.sumAmount = Math.abs(
            proxy.$fn.deepClone(item.diffSumAmount || 0)
          )
        }
        item.largeUnitQty = parseInt(item.calcQty / unitConvertCoefficient)
        item.smallUnitQty = parseInt(item.calcQty % unitConvertCoefficient)
        if (item.codeType === 1 || item.codeType === 4) {
          item.details = [proxy.$fn.deepClone(item)]
          item.details[0].inventoryDetailId = item.details[0].id
        }
        item.isGetRight = true
        item.copyGroupConcatIds = proxy.$fn.deepClone(item.groupConcatIds)
      })
      if (props.businessType === '1') {
        let group = _.groupBy(res.data, 'supplierId')
        let arr = Object.values(group)
        let options = []
        arr.forEach((item) => {
          options.push({
            id: item[0].supplierId,
            name: item[0].supplierName,
          })
        })
        tableInfo.value.data = arr[0]
        formInfo.value.data.supplierId = arr[0][0].supplierId
        formInfo.value.data.supplierName = arr[0][0].supplierName
        tableInfo.value.supplierOptions = options
        tableInfo.value.supplierGroupData = group
      } else {
        tableInfo.value.data = res.data
      }
    }
  })
}
function checkSupplier(item) {
  formInfo.value.data.supplierId = item.id
  formInfo.value.data.supplierName = item.name
  tableInfo.value.data = tableInfo.value.supplierGroupData[item.id]
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function formHandleEvent(event, num) {
  switch (event) {
    case 'businessType':
      let keyObj = {
        storeDepotName: 'name',
        storeDepotId: 'id',
        storeDeptName: 'deptName',
        storeDeptId: 'deptId',
      }
      setFormInfo(keyObj, {})
      setInfoAndList(num)
      setTableFieldList(num)
      if (num === '34') {
        selectStoreDepotInfo.value.query.subDepotId = props.baseData.depotId
      } else {
        selectStoreDepotInfo.value.query.subDepotId = ''
      }
      selectStoreDepotInfo.value.query.isCargoSpaceManage = 0
      if (num === '2' || num === '34') {
        selectStoreDepotInfo.value.query.isCargoSpaceManage = ''
      }
      showSetLocation.value = false
      tableInfo.value.fieldList.forEach((item) => {
        if (item.value === 'targetLocationNo') {
          item.hidden = true
        }
      })
      formInfo.value.data.businessType = num
      break
  }
}
function individualDetail(row, index) {
  //个体操作
  if (
    formInfo.value.data.businessType === '20' &&
    !formInfo.value.data.useApplicationId
  ) {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '请选择申请单号',
    })
    return
  }
  individualInfo.value.visible = true
  individualInfo.value.index = index
  individualInfo.value.tableRow = proxy.$fn.deepClone(row)
  individualInfo.value.details = proxy.$fn.deepClone(row.details || [])
  individualInfo.value.leftQuery.queryMap.id.value =
    row.copyGroupConcatIds || ''
  individualInfo.value.leftQuery.queryMap.productId.value = row.productId
  individualInfo.value.leftQuery.queryMap.price.value = row.price
  individualInfo.value.leftQuery.queryMap.supplierId.value = row.supplierId
  individualInfo.value.leftQuery.queryMap.storeBatchNumber.value =
    row.storeBatchNumber
  if (row.batchNumber) {
    individualInfo.value.leftQuery.queryMap.batchNumber = {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: row.batchNumber,
    }
  } else {
    individualInfo.value.leftQuery.queryMap.batchNumber = {
      queryType: 'NULL',
      queryCategory: 'AND',
      value: '',
    }
  }
  if (row.validityDate) {
    individualInfo.value.leftQuery.queryMap.validityDate = {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: row.validityDate,
    }
  } else {
    individualInfo.value.leftQuery.queryMap.validityDate = {
      queryType: 'NULL',
      ignoreEmptyValue: false,
      queryCategory: 'AND',
      value: null,
    }
  }
  if (row.productionDate) {
    individualInfo.value.leftQuery.queryMap.productionDate = {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: row.productionDate,
    }
  } else {
    individualInfo.value.leftQuery.queryMap.productionDate = {
      queryType: 'NULL',
      ignoreEmptyValue: false,
      queryCategory: 'AND',
      value: null,
    }
  }
}
function individualCallback(data, copyGroupConcatIds) {
  //个体返回
  let index = individualInfo.value.index
  let num = props.businessType
  let largeUnitQty = 0
  let smallUnitQty = 0
  let calcQty = 0
  if (data && data.length) {
    data.forEach((item) => {
      largeUnitQty = proxy.$fn.accAdd(largeUnitQty, item.largeUnitQty || 0)
      smallUnitQty = proxy.$fn.accAdd(smallUnitQty, item.smallUnitQty || 0)
      calcQty = proxy.$fn.accAdd(calcQty, item.calcQty || 0)
      item.inventoryDetailId = item.id
      if ((num === '2' || num === '34') && showSetLocation.value) {
        item.targetLocationNo =
          tableInfo.value.data[index].targetLocationNo || ''
        item.targetGoodsLocationId =
          tableInfo.value.data[index].targetGoodsLocationId || ''
        item.targetLocationTypeValue =
          tableInfo.value.data[index].targetLocationTypeValue || ''
        item.targetLocationType =
          tableInfo.value.data[index].targetLocationType || ''
      }
    })
    tableInfo.value.data[index].isGetRight = false
  } else {
    tableInfo.value.data[index].isGetRight = false
  }
  let unitConvertCoefficient =
    tableInfo.value.data[index].unitConvertCoefficient || 1
  let price = tableInfo.value.data[index].price || 0
  tableInfo.value.data[index].qty = proxy.$fn.accDiv(
    calcQty,
    unitConvertCoefficient
  )
  tableInfo.value.data[index].sumAmount = proxy.$fn.accDiv(
    proxy.$fn.accMul(calcQty, parseFloat(price)),
    unitConvertCoefficient
  )
  tableInfo.value.data[index].largeUnitQty = largeUnitQty
  tableInfo.value.data[index].smallUnitQty = smallUnitQty
  tableInfo.value.data[index].calcQty = calcQty
  tableInfo.value.data[index].details = data
  tableInfo.value.data[index].copyGroupConcatIds = copyGroupConcatIds
  if (props.businessType === '1') {
    tableInfo.value.supplierGroupData[formInfo.value.data.supplierId][index] =
      tableInfo.value.data[index]
  }
}
//删除产品
function removeProduct(selectRow = undefined) {
  if (
    formInfo.value.data.businessType === '20' &&
    !formInfo.value.data.useApplicationId
  ) {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '请选择申请单号',
    })
    return
  }
  if (selectRow && selectRow.productId) {
    tableInfo.value.data = tableInfo.value.data.filter(
      (row) => row !== selectRow
    )
    if (props.businessType === '1') {
      if (tableInfo.value.data.length) {
        tableInfo.value.supplierGroupData[formInfo.value.data.supplierId] =
          tableInfo.value.data
      } else {
        delete tableInfo.value.supplierGroupData[formInfo.value.data.supplierId]
        let arr = Object.values(tableInfo.value.supplierGroupData)
        if (arr.length) {
          let options = []
          arr.forEach((item) => {
            options.push({
              id: item[0].supplierId,
              name: item[0].supplierName,
            })
          })
          tableInfo.value.data = arr[0]
          formInfo.value.data.supplierId = arr[0][0].supplierId
          formInfo.value.data.supplierName = arr[0][0].supplierName
          tableInfo.value.supplierOptions = options
        } else {
          formInfo.value.data.supplierId = ''
          formInfo.value.data.supplierName = ''
          tableInfo.value.supplierOptions = {}
        }
      }
    }
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.value.data = tableInfo.value.data.filter(
          (row) => !tableInfo.value.selections.includes(row)
        )
        if (props.businessType === '1') {
          if (tableInfo.value.data.length) {
            tableInfo.value.supplierGroupData[formInfo.value.data.supplierId] =
              tableInfo.value.data
          } else {
            delete tableInfo.value.supplierGroupData[
              formInfo.value.data.supplierId
            ]
            let arr = Object.values(tableInfo.value.supplierGroupData)
            if (arr.length) {
              let options = []
              arr.forEach((item) => {
                options.push({
                  id: item[0].supplierId,
                  name: item[0].supplierName,
                })
              })
              tableInfo.value.data = arr[0]
              formInfo.value.data.supplierId = arr[0][0].supplierId
              formInfo.value.data.supplierName = arr[0][0].supplierName
              tableInfo.value.supplierOptions = options
            } else {
              formInfo.value.data.supplierId = ''
              formInfo.value.data.supplierName = ''
              tableInfo.value.supplierOptions = {}
            }
          }
        }
      })
  }
}
//选择领用出库单
function openUseApplication() {
  selectUseApplicationInfo.value.visible = true
}
function selectUseApplicationCallback(data) {
  if (data && data.id) {
    formInfo.value.data.useApplicationOrderNo = data.orderNo
    formInfo.value.data.useApplicationId = data.id
    formInfo.value.data.operateUserName = data.createUserName
    formInfo.value.data.operateUser = data.createUser
    formInfo.value.data.storeDepotName = data.depotName
    formInfo.value.data.storeDepotId = data.depotId
    formInfo.value.data.storeDeptName = data.deptName
    formInfo.value.data.storeDeptId = data.deptId
    getList(data.id)
  } else {
    formInfo.value.data.useApplicationOrderNo = ''
    formInfo.value.data.useApplicationId = ''
    formInfo.value.data.operateUserName = ''
    formInfo.value.data.operateUser = ''
    formInfo.value.data.storeDepotName = ''
    formInfo.value.data.storeDepotId = ''
    formInfo.value.data.storeDeptName = ''
    formInfo.value.data.storeDeptId = ''
  }
}
//选择部门
function selectConsumeDept() {
  deptInfo.visible = true
}
//选择仓库
function selectStoreDepot() {
  selectStoreDepotInfo.value.visible = true
}
function selectDeptCallback(data) {
  if (data && data.id) {
    formInfo.value.data.consumeDeptName = data.name
    formInfo.value.data.consumeDeptId = data.id
  } else {
    formInfo.value.data.consumeDeptName = ''
    formInfo.value.data.consumeDeptId = ''
  }
}
function selectStoreDepotCallBack(data = undefined) {
  let keyObj = {
    storeDepotName: 'name',
    storeDepotId: 'id',
    storeDeptName: 'deptName',
    storeDeptId: 'deptId',
  }
  let num = formInfo.value.data.businessType
  showSetLocation.value = false
  tableInfo.value.fieldList.forEach((item) => {
    if (item.value === 'targetLocationNo') {
      item.hidden = true
    }
    if (
      data &&
      data.id &&
      data.isCargoSpaceManage === 1 &&
      (num === '2' || num === '34')
    ) {
      if (item.value === 'targetLocationNo') {
        item.hidden = false
      }
    }
  })
  if (num === '2' || num === '34') {
    tableInfo.value.data.forEach((item) => {
      item.targetLocationNo = ''
      item.targetGoodsLocationId = ''
      item.targetLocationTypeValue = ''
      item.targetLocationType = ''
      item.details?.forEach((el) => {
        el.targetLocationNo = ''
        el.targetGoodsLocationId = ''
        el.targetLocationTypeValue = ''
        el.targetLocationType = ''
      })
    })
  }
  if (data && data.id) {
    if (data.isCargoSpaceManage === 1 && (num === '2' || num === '34')) {
      showSetLocation.value = true
    }
    setFormInfo(keyObj, data)
  } else {
    setFormInfo(keyObj, {})
  }
}
function save() {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    let list = proxy.$fn.deepClone(tableInfo.value.data)
    let details = list.filter((item) => {
      if (item.qty > 0) {
        if (
          (item.codeType === 2 || item.codeType === 3) &&
          item.details &&
          item.details.length
        ) {
          item.groupConcatIds = item.details.map((item) => item.id).toString()
        }
        if (
          (item.codeType === 1 || item.codeType === 4) &&
          formInfo.value.data.businessType === '1'
        ) {
          item.details[0].reason = item.reason
        }
        return item
      }
    })
    let data = proxy.$fn.deepClone(formInfo.value.data)
    data.isConsignBusiness = props.isConsignBusiness
    data.inventoryId = props.orderId
    if (!details.length) {
      proxy.$message({
        duration: 3500,
        type: 'warning',
        showClose: true,
        message: '请添加有效的产品',
      })
      return
    }
    if (data.businessType === '1') {
      let notSupplierList = []
      details.forEach((item) => {
        if (!item.supplierId || item.supplierId === -2) {
          notSupplierList.push(item)
        }
      })
      if (notSupplierList.length) {
        proxy.$message({
          message: `选择出库处理的产品存在无供应商的情况，请处理`,
          type: 'warning',
          duration: 3500,
          showClose: true,
        })
        return
      }
    }
    if (data.businessType === '20') {
      let commonName = details
        .filter((item) => item.calcQty > item.useApplicationCalcQty)
        .map((item) => item.commonName)
      if (commonName.length) {
        proxy.$message({
          message: `出库处理产品【${commonName}】的出库数量不能大于领用出库数，请处理`,
          type: 'warning',
          duration: 3500,
          showClose: true,
        })
        return
      }
    }
    data.mergeDetails = proxy.$fn.filterBlacklist(details)
    inventoriesInsertInventoryLossBusiness(data).then((resp) => {
      if (resp && resp.success) {
        proxy.$message({
          message: `保存成功`,
          type: 'success',
          duration: 3500,
          showClose: true,
        })
        if (props.businessType === '1') {
          delete tableInfo.value.supplierGroupData[
            formInfo.value.data.supplierId
          ]
          let arr = Object.values(tableInfo.value.supplierGroupData)
          if (arr.length) {
            let options = []
            arr.forEach((item) => {
              options.push({
                id: item[0].supplierId,
                name: item[0].supplierName,
              })
            })
            tableInfo.value.data = arr[0]
            formInfo.value.data.supplierId = arr[0][0].supplierId
            formInfo.value.data.supplierName = arr[0][0].supplierName
            tableInfo.value.supplierOptions = options
          } else {
            showDialog.value = false
            emits('callback')
          }
        } else {
          showDialog.value = false
          emits('callback')
        }
      }
    })
  })
}
// 根据定义值赋值给formInfo默认值
function setFormInfo(obj, info) {
  for (let k in obj) {
    formInfo.value.data[k] = info[obj[k]] || ''
  }
}
</script>

<style scoped lang="scss">
.batch-content {
  width: 100%;
  display: flex;
  .batch-content-item-left {
    width: 240px;
    padding-right: 10px;
    flex-shrink: 0;
  }
  .batch-content-item-right {
    flex: 1;
    width: 0;
  }
}
.supplier-item {
  cursor: pointer;
}
</style>
